-module(rtps_transport_sup).

%%% @doc
%%% Every domain includes a tarnsport supervisor which controls the
%%% transports for all participants and endpoints within the
%%% domain. Communication between domains is fully isolated. If some
%%% process within the domain, either participant or endpoint, needs a
%%% transport, the domain's transport supervisor will add a new
%%% transport or add the process to a already exisitng transport. A
%%% particular transport may combine traffic for one or more
%%% processes.

-behaviour(supervisor).

%% API
-export([start_link/0, add/6]).

%% Supervisor callbacks
-export([init/1]).

%%====================================================================
%% API functions
%%====================================================================

-spec add(Sup, Endpoint_pid, Locator, Local_guid, Remote_guid, Opts) -> {ok, Sender} when
      Sup :: pid(),
      Endpoint_pid :: pid(),
      Locator :: rtsp:locator(),
      Local_guid :: rtps:guid(),
      Remote_guid :: rtps:guid() | unknown,
      Opts :: [proplists:property()],
      Sender :: pid().
%% #doc Add a transport. If there is no transport available for the
%% Locator, a new transport process is created, otherwise, the calling
%% process is added to the existing transport with the
%% `rtps_transport:open/2' call.
add(Sup, Endpoint_pid, Locator, Local_guid, Remote_guid, Opts) ->
    Spec = #{id => Locator,
	     start => {rtps_transport, start_link, [Locator, Opts]},
	     restart => temporary},
    case supervisor:start_child(Sup, Spec) of
	{ok, Pid} ->
	    Pid;
	{error, {already_started, Pid}} ->
	    Pid
    end,
    rtps_transport:open(Pid, Endpoint_pid, Local_guid, Remote_guid).

start_link() ->
    supervisor:start_link(?MODULE, []).

%%====================================================================
%% Supervisor callbacks
%%====================================================================

%% @private
init([]) ->
    {ok, {#{strategy => one_for_one}, []}}.

%%====================================================================
%% Internal functions
%%====================================================================
